package com.eastcom.groovy.task.taskdirector.db
/**
 * Created by yuanyue on 2014-08-15.
 * 目的资源：数据库
 * 源资源：任何
 */

import com.eastcom.groovy.config.GroovyScript
import com.eastcom.groovy.config.TaskConfig
import com.eastcom.groovy.context.ServerContext
import com.eastcom.groovy.context.TaskContext
import com.eastcom.groovy.provider.DbContextProvider
import com.eastcom.groovy.provider.SpringContextProvider
import com.eastcom.groovy.task.Task
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.db.DbInfo
import com.eastcom.groovy.tools.db.Table
import com.eastcom.groovy.tools.file.GroovyUtil
import com.eastcom.groovy.tools.file.JaxbUtil
import com.eastcom.groovy.tools.TaskUtil

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.ResultSetExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.io.IOException;
import java.io.Serializable;
import java.sql.CallableStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor
import java.util.regex.Matcher
import java.util.regex.Pattern
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement

@XmlRootElement(name = "resource")
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
class Resource implements Serializable {
	@XmlElement(name = "name")
	String name
	@XmlElement(name = "timeFormat")
	String timeFormatArr
	@XmlElement(name = "dst")
	List<DstResource> dstResourceList
	@XmlElement(name = "src")
	List<SrcResource> srcResourceList
	@javax.xml.bind.annotation.XmlTransient
	String jobId

	public boolean init(String jobId) {
		this.jobId = jobId
		if (dstResourceList == null && srcResourceList == null) {
			println "目的资源或源资源不能为空！"
			return false
		}
		TaskConfig taskConfig = TaskContext.getTask(jobId).taskConfig
		if (timeFormatArr != null) {
			String[] timeFormatArr = timeFormatArr.split("\\s*,\\s*")
			//			timeFormatArr.each {
			//				TaskContext.timeFormatList.add(it)
			//			}
		}
		srcResourceList.each {
			it.init(jobId)
			TaskContext.taskConfig.put(jobId+"."+it.name, it)
		}
		dstResourceList.each { it.init(jobId) }
		TaskContext.taskConfig.put(jobId+".dstResource", dstResourceList)
	}
}

/**
 * 原始资源信息
 */
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
class SrcResource implements Serializable {
	private static Log logger = LogFactory.getLog(SrcResource.class)
	@XmlElement(name = "name")
	String name
	@XmlElement(name = "srcFiles")
	String srcFiles
	@XmlElement(name = "srcParseMethod")
	String srcParseMethod
	@XmlElement(name = "placeHolderIndex")
	String placeHolderIndex
	@javax.xml.bind.annotation.XmlTransient
	List<Integer> placeHolderIndexList
	@javax.xml.bind.annotation.XmlTransient
	List<List<Object>> insertParamList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	Object detailContext
	@javax.xml.bind.annotation.XmlTransient
	String jobId
	@javax.xml.bind.annotation.XmlTransient
	Object dstResource
	public boolean init(String jobId) {
		logger.debug("初始化源数据"+name+"开始。。。")
		if(srcFiles != null){
			GroovyScript configScript = new GroovyScript()
			TaskContext.taskMap.each { println it }
			println jobId
			println TaskContext.taskMap.get(jobId)
			configScript.scriptFileRootPath = TaskContext.taskMap.get(jobId).rootPath
			println configScript.scriptFileRootPath
			configScript.scriptFileName = TaskContext.taskMap.get(jobId).taskConfig.extern.executor.executorClass
			configScript.param = srcFiles + "," + jobId
			Class<?> clazz = GroovyUtil.loadScriptClass(configScript)
			GroovyObject clazzObj = (GroovyObject) clazz.newInstance()
			Object object = clazzObj.invokeMethod(srcParseMethod, (String) configScript.param)
			detailContext = object
			return detailContext == null ? false : true
		}
		this.jobId = jobId
		return true
	}

	public boolean reInit(Object dstResource,List<Integer> placeHolderIndexList) {
		this.dstResource = dstResource
		if (placeHolderIndexList != null && !placeHolderIndexList.empty) {
			this.placeHolderIndexList = placeHolderIndexList
		} else {
			//1-2,3-4,5,8-12
			this.placeHolderIndexList = new ArrayList<>()
			String[] placeHolderArrTemp = placeHolderIndex.split("\\s*,\\s*")
			placeHolderArrTemp.each {
				if(it.contains("-")){
					String[] placeHolderArr = it.split("\\s*-\\s*")
					int start = Integer.valueOf(placeHolderArr[0])
					int stop = Integer.valueOf(placeHolderArr[1])
					for(int i = start; i <= stop; i ++){
						this.placeHolderIndexList.add(i)
					}
				}else{
					this.placeHolderIndexList.add(Integer.valueOf(it))
				}

			}
		}
		detailContext.dbSrcResource.each { it.dstResource = dstResource }
		return true
	}



	public SrcResource deepClone() throws IOException, ClassNotFoundException {
		//将对象写到流中
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = new ObjectOutputStream(bo);
		oo.writeObject(this);
		//从流中读出来
		ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
		ObjectInputStream oi = new ObjectInputStream(bi);
		return (SrcResource) oi.readObject();
	}
}

/***
 * 采集目的资源信息
 */
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
class DstResource implements Serializable {
	private static Log logger = LogFactory.getLog(DstResource.class)
	@XmlElement(name = "name")
	String name
	@XmlElement(name = "type")
	String type
	@XmlElement(name = "dstDb")
	String dstDb
	@XmlElement(name = "dstTb")
	String dstTb
	@XmlElement(name="dstMaxTimeValue")
	String dstMaxTimeValue
	@XmlElement(name = "configureInsertSql")
	String configureInsertSql
	@XmlElement(name = "srcNames")
	String srcNames
	@XmlElement(name = "dstFields")
	String dstFields
	@javax.xml.bind.annotation.XmlTransient
	List<String> srcNameList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<SrcResource> srcResourceList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<String> dstFieldList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<Integer> dstFieldTypeList
	@javax.xml.bind.annotation.XmlTransient
	int[] sqlTypes
	@javax.xml.bind.annotation.XmlTransient
	String jobId
	@javax.xml.bind.annotation.XmlTransient
	List<List<Object>> insertDataList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	DbEngine dbEngine
	@javax.xml.bind.annotation.XmlTransient
	String insertSql = ""

	public boolean init(String jobId) {
		this.jobId = jobId
		int i = 0

		dstFieldTypeList = loadDb(dstDb, dstTb);
		//源数据表
		String[] srcNameArr = srcNames.split("\\s*,\\s*")

		srcNameArr.each { srcNameList.add(it) }
		if(dstFields == null){
			logger.error("目的数据库字段不能为空！")
			return false
		}
		sqlTypes = new int[dstFieldTypeList.size()]
		dstFieldTypeList.each {
			sqlTypes[i++] = it
		}
		if (configureInsertSql == null || configureInsertSql.equals("")) {
			insertSql = makeSql(dstFieldList, dstTb)
		} else {
			insertSql = configureInsertSql
		}
		logger.debug(insertSql)
		srcNameList.each {
			SrcResource srcResource = TaskContext.taskConfig.get(jobId+"."+it)
			if (srcResource == null) {
				logger.error("目的资源初始化失败！找不到源资源名：" + name + "!")
				return false
			}
			srcResource.reInit(this,null)
			srcResourceList.add(srcResource)
		}
	}

	public Timestamp queryMaxTimeOfDstTb() {
		DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
		ServerContext.setCustomerType(dstDb)
		Map<String, Object> result = dbEngine.getJdbcUtil().queryForMap("select "+dstMaxTimeValue+" MAX_DSTTIME from "+dstTb)
		return result.get("MAX_DSTTIME") != null ? result.get("MAX_DSTTIME") : new Timestamp(new Date().getTime())
	}

	public int[] insertData() {
		int recordCount = srcResourceList.get(0).insertParamList.size()
		for(int i = 0; i < recordCount; i++){
			List<Object> record = new ArrayList<>()
			srcResourceList.each {
				List<Object> srcParamList = it.insertParamList.get(i)
				List<Integer> placeHolder = it.placeHolderIndexList
				for(int j = 0; j < srcParamList.size(); j++){
					record.add(placeHolder.get(j),srcParamList.get(j))
				}
			}
			insertDataList.add(record)
		}
		dbEngine = SpringContextProvider.getBean("dbEngine")
		List<Object[]> insertParamList = new ArrayList<>()
		insertDataList.each {
			Object[] data = it.toArray()
			insertParamList.add(data)
		}
		ServerContext.setCustomerType(dstDb);
		try {
			logger.debug("insertParamList.size="+insertParamList.size())
			if(insertParamList.size() == 0){
				logger.debug("插入数量为0！")
				return null
			}
			int[] res = dbEngine.getJdbcUtil().batchUpdate(insertSql, insertParamList, sqlTypes);
			logger.debug("插入数量="+res[0]+"--"+res[1])
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}
	}

	List<Integer> loadDb(String dstDb, String dstTb) {
		String db = dstDb.trim()
		String tb = dstTb.trim()

		List<Integer> dstFieldTypeList = new ArrayList<>()
		if (ServerContext.dbMap.containsKey(db)) {
			DbInfo dbInfo = ServerContext.dbMap.get(db)
			Map<String, Table> tables = dbInfo.tables
			if (tables.containsKey(db)) {
				println "已存在表[" + tb + "]信息。。。"
			} else {
				println "正在加载表[" + tb + "]信息。。。"
				DbContextProvider dbContextProvider = new DbContextProvider()
				if (!dbContextProvider.loadDbSource(db, tb)) {
					println "加载表[" + tb + "]信息失败！"
					return false
				}
				println "查询表[" + tb + "]信息成功！"
			}
		} else {
			println "正在加载表[" + tb + "]信息。。。"
			DbContextProvider dbContextProvider = new DbContextProvider()
			if (!dbContextProvider.loadDbSource(db, tb)) {
				println "加载表[" + db + "]信息失败！"
				return false
			}
			println "查询表[" + db + "]信息成功！"
		}
		if(dstFields.trim().equalsIgnoreCase("ALL")){
			logger.debug("目的数据库配置ALL，使用所有字段!")
			dstFieldList.addAll(ServerContext.dbMap.get(dstDb.trim()).tables.get(dstTb.trim()).feildName)
			logger.debug("dstFieldList.size="+dstFieldList.size())
		}else {
			String[] fieldArr  = dstFields.split("\\s*,\\s*")
			fieldArr.each { dstFieldList.add(it) }
		}
		if (!checkDstDbFeilds(db, tb, dstFieldList)) {
			println "配置表字段与实际或者缓存中不一致！请检查配置和数据库信息是否一致！"
			return false
		}
		dstFieldList.each {
			int index = ServerContext.dbMap.get(db).getTables().get(tb).feildName.indexOf(it)
			dstFieldTypeList.add(ServerContext.dbMap.get(db).getTables().get(tb).feildType.get(index))
		}
		return dstFieldTypeList
	}

	boolean checkDstDbFeilds(String db, String tb, List<String> dstFieldList) {
		if (ServerContext.dbMap.get(db).tables.get(tb).feildName.containsAll(dstFieldList)) {
			return true
		}
		return false
	}

	String makeSql(List<String> fieldList, String table) {
		StringBuffer sqlBuffer = new StringBuffer()
		int i = 0
		sqlBuffer.append("insert into " + table + "(")
		fieldList.each {
			sqlBuffer.append(it)
			i++
			if (i < fieldList.size()) {
				sqlBuffer.append(",")
			}
		}
		sqlBuffer.append(") values (")
		for (int s = 0; s < fieldList.size(); s++) {
			sqlBuffer.append("?")
			if (s < fieldList.size() - 1) {
				sqlBuffer.append(",")
			}
		}
		sqlBuffer.append(")")
		return sqlBuffer.toString()
	}
}



/**
 * Created by yuanyue on 2014-08-13.
 */
@XmlRootElement(name = "srcResource")
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.NONE)
class DbSrcResourceList {
	@XmlElement(name = "resource")
	List<DbSrc> dbSrcResource
}

@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class DbSrc implements Serializable {
	@javax.xml.bind.annotation.XmlTransient
	Log logger = LogFactory.getLog(this.class)
	@XmlElement(name = "id")
	String id;
	@XmlElement(name = "db")
	String db;
	@XmlElement(name = "tb")
	String tb;
	@XmlElement(name = "srcMaxTimeValue")
	String srcMaxTimeValue;
	@XmlElement(name = "sql")
	String sql
	@javax.xml.bind.annotation.XmlTransient
	List<String> ctxtFunction = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<List<String>> ctxtParamString = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<String> paramFunction = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<List<String>> paramParamString = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<Object> paramObject = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	List<Object> ctxtObject = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	String sqlValue
	@javax.xml.bind.annotation.XmlTransient
	String sqlContext
	@javax.xml.bind.annotation.XmlTransient
	int[] paramTypes
	@javax.xml.bind.annotation.XmlTransient
	Object[] paramValues
	@javax.xml.bind.annotation.XmlTransient
	List<String> paramTypeList = new ArrayList<>()
	@javax.xml.bind.annotation.XmlTransient
	final String ctxtRegex = "\\\$\\{CTXT:(\\w+)\\(([^\\)\\}]*)\\)\\}"
	@javax.xml.bind.annotation.XmlTransient
	final String paramRegex = "\\\$\\{PARAM\\[(\\w+)\\]:(\\w+)\\(([^\\)\\}]*)\\)\\}"
	@XmlElement
	Object dstResource
	public boolean init() {
		String context = sql
		sqlContext = new String(sql)
		Pattern ctxtPattern = Pattern.compile(ctxtRegex)
		Pattern paramPattern = Pattern.compile(paramRegex)
		Matcher ctxtMatcher = ctxtPattern.matcher(context)
		boolean isFind = false
		isFind = ctxtMatcher.find()
		println(isFind)
		while (isFind) {
			println ctxtMatcher.groupCount()
			String function = ctxtMatcher.group(1)
			println(function)
			logger.debug("function=" + function)
			ctxtFunction.add(function)
			String paramString = ctxtMatcher.group(2)
			List<String> param = new ArrayList<>()
			if (paramString == null || paramString.equals("")) {
				param.add("NULL")
				ctxtParamString.add(param)
			} else {
				String[] paramArr = paramString.split("\\s*,\\s*")
				paramArr.each { param.add(it) }
				ctxtParamString.add(param)
			}

			isFind = ctxtMatcher.find()
		}
		Matcher paramMatcher = paramPattern.matcher(context)
		isFind = paramMatcher.find()
		while (isFind) {
			println paramMatcher.groupCount()
			String paramType = paramMatcher.group(1)
			paramTypeList.add(paramType)
			String function = paramMatcher.group(2)
			println(function)
			paramFunction.add(function)
			String paramString = paramMatcher.group(3)
			List<String> param = new ArrayList<>()
			if (paramString == null || paramString.equals("")) {
				param.add("NULL")
				paramParamString.add(param)
			} else {
				String[] paramArr = paramString.split("\\s*,\\s*")
				paramArr.each { param.add(it) }
				paramParamString.add(param)
			}
			isFind = paramMatcher.find()
		}
		context = context.replaceAll(paramRegex, "?")
		for (int i = 0; i < paramFunction.size(); i++) {
			Object res = null
			List<String> paramList = paramParamString.get(i)
			if(paramFunction.get(i).equalsIgnoreCase("queryMaxTimeOfDstTb")){
				res = new Timestamp(new Date().getTime())
			}else if(paramFunction.get(i).equalsIgnoreCase("queryMaxTimeOfSrcTb")){
				res = this.queryMaxTimeOfSrcTb()
			}else{
				res = this.invokeMethod(paramFunction.get(i), paramList)
			}
			paramObject.add(res)
		}
		paramValues = paramObject.toArray()
		for (int i = 0; i < ctxtFunction.size(); i++) {
			List<String> paramList = ctxtParamString.get(i)

			Object res = this.invokeMethod(ctxtFunction.get(i), paramList)
			ctxtObject.add(res)
		}
		paramTypes = new int[paramTypeList.size()]
		for (int i = 0; i < paramTypeList.size(); i++) {
			String type = paramTypeList.get(i)
			if (type.equalsIgnoreCase("TIMESTAMP")) {
				paramTypes[i] = Types.TIMESTAMP
			} else if (type.equalsIgnoreCase("INTEGER")) {
				paramTypes[i] = Types.INTEGER
			} else if (type.equalsIgnoreCase("NUMERIC")) {
				paramTypes[i] = Types.NUMERIC
			} else if (type.equalsIgnoreCase("DOUBLE")) {
				paramTypes[i] = Types.DOUBLE
			} else if (type.equalsIgnoreCase("FLOAT")) {
				paramTypes[i] = Types.FLOAT
			} else if (type.equalsIgnoreCase("DATE")) {
				paramTypes[i] = Types.DATE
			} else if (type.equalsIgnoreCase("CLOB")) {
				paramTypes[i] = Types.CLOB
			} else if (type.equalsIgnoreCase("BIGINT")) {
				paramTypes[i] = Types.BIGINT
			} else if (type.equalsIgnoreCase("BINARY")) {
				paramTypes[i] = Types.BINARY
			} else if (type.equalsIgnoreCase("VARCHAR")) {
				paramTypes[i] = Types.VARCHAR
				//ORACLE nclob,nvarchar2
			} else if (type.equalsIgnoreCase("OTHER")) {
				paramTypes[i] = Types.OTHER
			} else {
				logger.error("sql 鍙傛暟绫诲瀷[" + type + "]鏃犳硶璇嗗埆锛�")
				return false
			}
		}
		return true
	}
	public Timestamp queryMaxTimeOfSrcTb() {
		DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
		ServerContext.setCustomerType(db)
		Map<String, Object> result = dbEngine.getJdbcUtil().queryForMap("select "+srcMaxTimeValue +" MAX_SRCTIME"+" from "+tb)
		return result.get("MAX_SRCTIME") != null ? result.get("MAX_SRCTIME") : new Timestamp(new Date().getTime())

	}
	public String getQuerySqlValue() {
		paramObject.clear()
		ctxtObject.clear()
		String sql = this.sql
		sql = sql.replaceAll(paramRegex, "?")
		for (int i = 0; i < paramFunction.size(); i++) {
			List<String> paramList = paramParamString.get(i)
			Object res = null;
			if(paramFunction.get(i).equalsIgnoreCase("queryMaxTimeOfDstTb")){
				DstResource dst = dstResource
				res = dst.queryMaxTimeOfDstTb()
			}else if(paramFunction.get(i).equalsIgnoreCase("queryMaxTimeOfSrcTb")){
				res = this.queryMaxTimeOfSrcTb()
			}else{
				res = this.invokeMethod(paramFunction.get(i), paramList)
			}
			logger.debug(res)
			paramObject.add(res)
		}
		paramValues = paramObject.toArray()

		for (int i = 0; i < ctxtFunction.size(); i++) {
			List<String> paramList = ctxtParamString.get(i)
			Object res = this.invokeMethod(ctxtFunction.get(i), paramList)
			ctxtObject.add(res)
			sql = sql.replaceFirst(ctxtRegex, (String) res)
			logger.debug("temp sql = " + sql)
		}
		logger.debug("SQL=" + sql)
		return sql
	}

	public Timestamp getFirstDayOfSpecialMonth(List<String> afterNow) {
		Timestamp timestamp = new Timestamp(new Date().getTime())
		Calendar calendar = Calendar.getInstance()
		calendar.setTime(timestamp)
		calendar.add(Calendar.MONTH, Integer.valueOf(afterNow.get(0)))
		calendar.set(Calendar.DAY_OF_MONTH, 1)
		calendar.set(Calendar.HOUR_OF_DAY, 0)
		calendar.set(Calendar.MINUTE, 0)
		calendar.set(Calendar.SECOND, 0)
		calendar.set(Calendar.MILLISECOND, 0)
		return new Timestamp(calendar.getTime().getTime())
	}
	//timeFormat, String afterNow
	public String getContextByMonth(List<String> param) {
		param.each {
			logger.debug("param = " + it)
		}
		Calendar calendar = Calendar.getInstance()
		calendar.setTime(new Date())
		calendar.add(Calendar.MONTH, Integer.valueOf(param.get(0)))
		calendar.set(Calendar.DAY_OF_MONTH, 1)
		calendar.set(Calendar.HOUR_OF_DAY, 0)
		calendar.set(Calendar.MINUTE, 0)
		calendar.set(Calendar.SECOND, 0)
		calendar.set(Calendar.MILLISECOND, 0)
		SimpleDateFormat dateFormat = new SimpleDateFormat(param.get(1))
		String result = dateFormat.format(calendar.getTime())
		return result
	}

	//2014-04-11 00:00:00
	public Timestamp getTimeParamByDay(List<String> afterNow) {
		Timestamp timestamp = new Timestamp(new Date().getTime())
		Calendar calendar = Calendar.getInstance()
		calendar.setTime(timestamp)
		calendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(afterNow.get(0)))
		calendar.set(Calendar.HOUR_OF_DAY, 0)
		calendar.set(Calendar.MINUTE, 0)
		calendar.set(Calendar.SECOND, 0)
		calendar.set(Calendar.MILLISECOND, 0)
		return new Timestamp(calendar.getTime().getTime())
	}
	public String getTimeContextByDay(List<String> param) {
		Calendar calendar = Calendar.getInstance()
		calendar.setTime(new Date())
		calendar.add(Calendar.MONTH, Integer.valueOf(param.get(0)))
		calendar.set(Calendar.HOUR_OF_DAY, 0)
		calendar.set(Calendar.MINUTE, 0)
		calendar.set(Calendar.SECOND, 0)
		calendar.set(Calendar.MILLISECOND, 0)
		SimpleDateFormat dateFormat = new SimpleDateFormat(param.get(1))
		String result = dateFormat.format(calendar.getTime())
		return result
	}
}


public Object getSrc(String param) {
	String[] pArr = param.split(",")
	DbSrcResourceList testXml = JaxbUtil.converyFileToJavaBean(TaskContext.getTask(pArr[1]).getRootPath() + "/" + pArr[0], "UTF-8", DbSrcResourceList.class)
	println(TaskContext.allTask.size())
	testXml.dbSrcResource.each { it.init() }
	return testXml
}

public boolean initJob(String jobId){
	Log logger = LogFactory.getLog(this.class)
	String rootPath = TaskContext.taskMap.get(jobId).getRootPath()
	if(rootPath == null){
		logger.error("任务根目录为空！")
		return false
	}
	Resource resource = JaxbUtil.converyFileToJavaBean(rootPath+"/"+TaskContext.getTask(jobId).taskConfig.extern.config.configFile,"UTF-8",Resource.class)
	resource.init(jobId)
	logger.debug("资源初始换结束！")
	//	List<DstResource> dstResourceList = resource.dstResourceList
	//	TaskContext.taskConfig.put(jobId+".dstResource", dstResourceList)
}

/**
 * 鎵ц鏂规硶
 * @param jobId
 */
public boolean doJob(String jobId) {
	DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
	Log logger = LogFactory.getLog(this.getClass())
	List<DstResource> dstResourceList = TaskContext.taskConfig.get(jobId+".dstResource")
	dstResourceList.each {
		List<String> recordFieldList = it.dstFieldList
		it.insertDataList.clear()
		it.srcResourceList.each {
			it.insertParamList.clear()
			List<Integer> fieldIndexList = it.placeHolderIndexList
			DbSrcResourceList dbSrcResourceList = it.detailContext
			List<List<Object>> paramList = it.insertParamList
			List<Map<String, Object>> totalResult = new ArrayList<>()
			dbSrcResourceList.dbSrcResource.each {
				it.sqlValue = it.getQuerySqlValue()
			}
			DbSrc dbSrcResource = dbSrcResourceList.dbSrcResource.get(0)
			ServerContext.setCustomerType(dbSrcResource.db)
			List<Map<String, Object>> result = null;
			try {
				logger.debug(dbSrcResource.paramValues+"--"+dbSrcResource.paramTypes)
				result = dbEngine.getJdbcUtil().queryForList(dbSrcResource.sqlValue, dbSrcResource.paramValues, dbSrcResource.paramTypes);
				result.each { totalResult.add(it) }
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace()
			}
			//多个资源查询结果拼接
			for (int i = 1; i < dbSrcResourceList.dbSrcResource.size(); i++) {
				DbSrc dbSrc = dbSrcResourceList.dbSrcResource.get(i)
				ServerContext.setCustomerType(dbSrc.db)
				result = null;
				try {
					result = dbEngine.getJdbcUtil().queryForList(dbSrc.sqlValue, dbSrc.paramValues, dbSrc.paramTypes);
					if (result.size() != totalResult.size()) {
						return false
					}
					for (int j = 0; j < result.size(); j++) {
						Map<String, Object> res = result.get(j)
						totalResult.get(j).putAll(res)
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			totalResult.each {
				List<Object> record = new ArrayList<>()
				for (int k = 0; k < fieldIndexList.size(); k++) {
					int index = fieldIndexList.get(k)
					String fieldName = recordFieldList.get(index)
					Object value = it.get(fieldName)
					record.add(value)
				}
				paramList.add(record)
			}
		}
		ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringContextProvider.getBean("threadPool")
		threadPoolTaskExecutor.execute(
				new Runnable() {
					@Override
					void run() {
						Thread.currentThread().setName(jobId)
						it.insertData()
					}
				}
				)
	}
	return true
}







